package com.project.smms.controller;

import com.project.smms.pojo.Order;
import com.project.smms.pojo.User;
import com.project.smms.service.OrderService;
import com.project.smms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Collection;
import java.util.List;

/**
 * @author 莫息涛
 * @Description: 订单的控制器
 * @date 2020/3/6 16:28
 */
@Controller
public class OrderController {

    @Autowired
    private OrderService orderService;
    
    @Autowired
    private UserService userService;

    @RequestMapping("/selectOrder")
    public String selectOrder(Model model){
        Collection<Order> orders = orderService.selectOrder();
        model.addAttribute("orders",orders);
        return "order";
    }

    @RequestMapping("/deleteOrder/{order_id}")
    public String deleteOrder(@PathVariable("order_id") Integer id, Model model){
        try {
            orderService.deleteOrder(id);
        }catch (Exception e){
            return "errordata";
        }finally {
            Collection<Order> orders = orderService.selectOrder();
            model.addAttribute("orders",orders);
        }
        return "order";
    }

    @RequestMapping("/toAddOrderPage")
    public String toAddPage(Model model){
        List<User> users = userService.selectUser();
        model.addAttribute("ordersuser",users);
        return "addorder";
    }

    @RequestMapping("/addOrder")
    public String addOrder(Order order, Model model){
        try {
            orderService.addOrder(order);
        }catch (Exception e){
            return "errordata";
        }finally {
            Collection<Order> orders = orderService.selectOrder();
            model.addAttribute("orders",orders);
        }
        return "order";
    }

    @RequestMapping("/toUpdateOrderPage/{order_id}")
    public String toUpdatePage(@PathVariable("order_id") Integer id,Model model){
        Order order = orderService.selectOrderById(id);
        List<User> users = userService.selectUser();
        model.addAttribute("ordersuser",users);
        model.addAttribute("updateorder",order);
        return "updateorder";
    }

    @RequestMapping("/updateOrder")
    public String updateOrder(Order order, Model model){
        try {
            orderService.updateOrder(order);
        }catch (Exception e){
            return "errordata";
        }finally {
            Collection<Order> orders = orderService.selectOrder();
            model.addAttribute("orders",orders);
        }
        return "order";
    }
}
